package com.nulldev.util.security.encryptAPI.impls.rabbit;

import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class Rabbit extends Encryptor {
	private final byte[] key;
	private final RabbitCipher cipher;

	public Rabbit(final String key) {
		super("encryptapi.tp.rabbit", new String[]
			{ "Rabbit" }, key);
		this.key = key.getBytes();
		this.cipher = new RabbitCipher();
		this.cipher.setupKey(this.key);
	}

	public Rabbit(final byte[] key) {
		super("encryptapi.tp.rabbit", new String[]
			{ "Rabbit" }, key);
		this.key = key;
		this.cipher = new RabbitCipher();
		this.cipher.setupKey(key);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			final byte[] f = (byte[]) o;
			this.cipher.crypt(f);
			return f;
		} else if (o instanceof String) {
			final byte[] f = ((String) o).getBytes();
			this.cipher.crypt(f);
			return f;
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			final byte[] f = (byte[]) o;
			this.cipher.crypt(f);
			return Base64.encodeBase64String(f);
		} else if (o instanceof String) {
			final byte[] f = ((String) o).getBytes();
			this.cipher.crypt(f);
			return Base64.encodeBase64String(f);
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String s) {
		final byte[] f = Base64.decodeBase64(s);
		this.cipher.crypt(f);
		return new String(f);
	}

	@Override
	public byte[] decryptToBytes(byte[] b) {
		this.cipher.crypt(b);
		return b;
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return new String(this.key);
	}
}
